package admin

import (
	"fmt"
	"hello/app/http/controllers"
	"hello/app/models"
	captchaService "hello/lib/captcha"
	"hello/lib/grouter"
	"hello/lib/view"
	"net/http"
)

type Auth struct {
	controllers.Base
	BaseModel models.Admin
}

func NewAuth() Auth {
	return Auth{}
}

// 登录页面
func (mc *Auth) LoginForm(w http.ResponseWriter, _ *http.Request) {
	fileName := "admin/auth/login"
	view.RenderSingeFile(w, fileName, view.D{}, fileName)
}

// 登陆后的首页 展示layout
func (mc *Auth) AdminIndex(w http.ResponseWriter, _ *http.Request) {
	//页面还要define定义才能找到模板
	view.RenderTemplate(w, "layout", view.D{}, "admin.index.layout")
}

//获取验证码
func (mc *Auth) GetCaptcha(w http.ResponseWriter, _ *http.Request) {
	detail := captchaService.GetCaptchaAndId(4)
	mc.SuccessJson(w, detail, "")
}

//登录
func (mc *Auth) Login(w http.ResponseWriter, r *http.Request) {
	username := r.PostFormValue("username")
	password := r.PostFormValue("password")
	captchaId := r.PostFormValue("captchaId")
	captcha := r.PostFormValue("captcha")
	err, admin := mc.BaseModel.Attempt(captchaId, captcha, username, password)
	if err != nil {
		mc.ErrorJson(w, "", err.Error())
		return
	}
	sessionData, err := mc.BaseModel.GetAdminBySession(r)
	if err != nil {
		mc.ErrorJson(w, "", err.Error())
		return
	}
	sessionData.Values["authenticated"] = true
	sessionData.Values["auth_admin_id"] = admin.ID
	fmt.Println(sessionData)
	fmt.Println(admin)
	err = sessionData.Save(r, w)
	if err != nil {
		mc.ErrorJson(w, "", err.Error())
		return
	}
	detail := make(map[string]string, 1)
	//helper := new(myhelpers.Helper)
	//helper.GetAdminPath("index")
	detail["url"] = grouter.Name2URL("admin.layout")
	mc.SuccessJson(w, detail, "登录成功，等待跳转")
}

//修改用户资料页面
func (mc *Auth) AdminEdit(w http.ResponseWriter, r *http.Request) {

}

//更新用户资料
func (mc *Auth) AdminUpdate(w http.ResponseWriter, r *http.Request) {

}

//登出
func (mc Auth) Logout(w http.ResponseWriter, r *http.Request) {

	session, _ := mc.BaseModel.GetAdminBySession(r)
	delete(session.Values, "authenticated")
	delete(session.Values, "auth_admin_id")
	_ = session.Save(r, w)
	url := grouter.Name2URL("adminlogin")
	http.Redirect(w, r, url, http.StatusFound)
	return
}
